import { BillTag } from '@/components';
import { formatFloat, getAverage } from '@/utils';
import { useRef, useState, useEffect, useMemo } from 'react';
import { Member } from '@/types';
import toast from 'react-hot-toast';
// 组件
import Caculator from './Caculator';
import CategorySelector from './CategorySelector';
import DescEditor from './DescEditor';
import MembersSelector from './MembersSelector';
import AccountMode from './AccountMode';

import useBillEditor from './useBillEditor';
import { useGlobalVar } from '@/hooks';

const getAverageDetail = (account, members) => {
   const arr = [];
   const value = getAverage(account, members.length);
   members.forEach((user) => {
      arr.push({
         userId: user.userId,
         account: value,
      });
   });

   return arr;
};

const Bill = () => {
   const { data, loading, isNew, addBill, updateBill } = useBillEditor();
   const { user } = useGlobalVar();

   const categoryRef = useRef<{ value: string }>();
   const descRef = useRef<{ value: string }>();

   const [account, setAccount] = useState(data.account);
   const [mode, setMode] = useState(data.mode);
   const [members, setMembers] = useState(data.members);
   const [details, setDetails] = useState(data.details);

   // 自定义模式时选中的标签
   const [activeTag, setActiveTag] = useState('');
   const handleClickTag = (userId) => {
      setActiveTag(userId);
   };
   const selectDetail = details.find((item) => item.userId === activeTag);
   const handleChangeDetailAccount = (value) => {
      selectDetail.account = value;
      setDetails([...details]);
   };

   const handleChangeAccount = (value) => {
      setAccount(value);
   };

   // 修改成员
   const handleChangeMembers = (input: Array<Member>) => {
      setActiveTag('');
      setMembers(input);
      // 如果是自定义的，同时调整details
      if (mode !== 'average') {
         const map = new Map();
         details.forEach((item) => {
            map.set(item.userId, item.account);
         });
         let _details = [];
         input.forEach((member) => {
            if (map.has(member.userId)) {
               _details.push({ ...member, account: map.get(member.userId) });
            } else {
               _details.push({ ...member, account: 0 });
            }
         });
         setDetails(_details);
      }
   };

   // 更新不同模式下的总金额
   useEffect(() => {
      if (mode !== 'average') {
         const nums = details.map((item) => item.account);
         if (nums.some((item) => isNaN(item))) {
            setAccount('--');
         } else {
            const sum = nums.reduce((acc, cur) => Number(acc) + Number(cur), 0);
            setAccount(formatFloat(sum));
         }
      } else {
         // setAccount('0');
      }
   }, [details, mode]);

   // 切换模式
   const handleChangeMode = (value) => {
      setMode(value);
      setActiveTag('');
      setDetails(members.map((item) => ({ account: 0, ...item })));
   };

   const handleComplete = () => {
      if (members.length === 0) {
         return toast.error('请选择成员');
      }
      if (!descRef.current || !categoryRef.current) return;

      const data = {
         bill_desc: descRef.current.value,
         account: Number(account),
         category: categoryRef.current.value,
         members: members.map((item) => item.userId),
         details: [],
         mode,
      };

      if (mode === 'average') {
         data.details = getAverageDetail(account, members);
      } else {
         if (details.some((item) => isNaN(item.account))) {
            return toast.error('请输入合法的金额');
         }
         data.details = details.map((item) => ({
            ...item,
            account: Number(item.account),
         }));
      }

      if (isNew) {
         addBill(data);
      } else {
         updateBill(data);
      }
   };

   if (loading) return <div>Loading...</div>;

   return (
      <div className="mx-4">
         <CategorySelector ref={categoryRef} data={data.category}>
            {account}
         </CategorySelector>
         <div className="color-disabled my-2">
            <div className="my-2 border-t h-0 border-dashed"></div>
            <DescEditor value={data.desc} ref={descRef} />
            <MembersSelector
               initValue={members}
               onChange={handleChangeMembers}
            />
            <AccountMode value={mode} onChange={handleChangeMode} />
            <div className="mt-2 w-full flex p-1.5 border border-dashed border-stone-300 bg-white flex-wrap">
               {mode === 'average' && (
                  <BillTag
                     label="人均"
                     value={getAverage(account, members.length)}
                  />
               )}

               {mode !== 'average' && (
                  <>
                     {details.length === 0 ? (
                        <div>请选择成员</div>
                     ) : (
                        details.map((item) => (
                           <BillTag
                              label={
                                 user.username === item.username
                                    ? '我'
                                    : item.username
                              }
                              value={item.account}
                              key={item.userId}
                              onClick={handleClickTag.bind(null, item.userId)}
                              active={activeTag === item.userId}
                           />
                        ))
                     )}
                  </>
               )}
            </div>
            {mode !== 'average' && (
               <>
                  <div className="color-disabled text-xs mt-1">
                     *点击用户标签进行编辑
                  </div>
                  <div className="my-2">
                     <div
                        className="w-12 h-12 rounded-full flex justify-center items-center shadow-md bg-white ml-auto"
                        onClick={handleComplete}
                     >
                        完成
                     </div>
                  </div>
               </>
            )}
         </div>

         {mode === 'average' && (
            <Caculator
               data={account}
               onComplete={handleComplete}
               onChange={handleChangeAccount}
            />
         )}

         {selectDetail && (
            <Caculator
               isSimple={true}
               data={selectDetail.account}
               onChange={handleChangeDetailAccount}
            />
         )}
      </div>
   );
};

export default Bill;
